const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::staff');
const router = require('koa-router')();
exports = module.exports = router;
const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectId;

const staff_service = require(global.prefixPath +'/services/staff');

router.get('/staffs', async (ctx, next) => {
	ctx.checkQuery('q').notEmpty("query param is missing!").isJSON("param must be a json string!");

	if (ctx.errors) {
		ctx.status = 400;
		ctx.body = ctx.errors;
		return;
	}

	let q = JSON.parse(ctx.query.q);

	try {
		let result = await staff_service.find(q);
		ctx.body = result;
	} catch (err) {
		throw err;
	}

});

/**
 *
 */
router.get('/staff/:id', async (ctx, next) => {
	try {
		let staff_id = ctx.params.id;
		let result = await staff_service.findById(staff_id);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 添加员工信息
 */
router.post('/staff', async (ctx, next) => {
	try {
		let staff = ctx.request.body;
		let result = await staff_service.insert(staff);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 修改员工信息
 */
router.put('/staff/:id', async (ctx, next) => {
	try {
		let staff_id = ctx.params.id;
		let staff = ctx.request.body;
		staff._id = new ObjectId(staff_id);
		let result = await staff_service.save(staff);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 删除员工信息
 */
router.delete('/staff/:id', async (ctx, next) => {
	try {
		let staff_id = ctx.params.id;
		let result = await staff_service.delById(staff_id);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});